import os
import pathlib
import random
import sys
from datetime import timedelta

import django
import faker
from django.utils import timezone

# 将项目根目录添加到 Python 的模块搜索路径中
back = os.path.dirname
BASE_DIR = back(back(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myblogs.settings")
    django.setup()

    from myaccount.models import User
    from article.models import Category, Article, Tag,BigCategory,Keyword
    from course.models import Course
    from comments.models import Comment


    # 清除旧数据
    print('clean database')
    Article.objects.all().delete()
    Category.objects.all().delete()
    Tag.objects.all().delete()
    # Comment.objects.all().delete()
    User.objects.all().delete()
    BigCategory.objects.all().delete()
    Keyword.objects.all().delete()
    Course.objects.all().delete()

    # 使用 django 的 ORM API 生成博客用户、分类、标签以及一篇 Markdown 测试文章
    print('create a blog user')
    user = User.objects.create_superuser('admin', 'admin@hellogithub.com', 'admin')

    print("创建教程")
    course_list = ['我爱python','Linux从入门到超神','从天上到地上']
    for course in course_list:
        Course.objects.create(title=course)

    print("创建关键字")
    keyword_list = ['python','nginx','开源','微软','Linux','Centos']
    for key in keyword_list:
        Keyword.objects.create(name=key)

    print("创建大目录")
    bigcategory_list = ["拥抱开源","虚拟化","容器","分享","阅读"]

    for cate in bigcategory_list:
        m = random.sample('abcdefghijklmnopqrstuvwxyz', 5)
        s = ''.join(m)
        BigCategory.objects.create(name=cate,slug=s,description=s,keywords=s)


    category_list = ['Python学习笔记', '开源项目', '工具资源', '程序员生活感悟', 'test category']
    tag_list = ['django', 'Python', 'Pipenv', 'Docker', 'Nginx', 'Elasticsearch', 'Gunicorn', 'Supervisor', 'test']
    a_year_ago = timezone.now() - timedelta(days=365)

    print('create categories and tags')
    for cate in category_list:
        m = random.sample('abcdefghijklmnopqrstuvwxyz', 5)
        s = ''.join(m)
        Category.objects.create(name=cate,bigcategory=random.choice(BigCategory.objects.all()),slug=s,description=s)

    for tag in tag_list:
        Tag.objects.create(name=tag)




    tag1 = random.choice(Tag.objects.all())
    tag2 = random.choice(Tag.objects.all())
    keyword = random.choice(Keyword.objects.all())


    m = random.sample('abcdefghijklmnopqrstuvwxyz', 5)
    s = ''.join(m)
    article = Article.objects.create(
        title ='Markdown 与代码高亮测试',
        body = pathlib.Path(BASE_DIR).joinpath('scripts', 'md.sample').read_text(encoding='utf-8'),
        category = random.choice(Category.objects.all()),
        author = user,
        slug = s,
        course = random.choice(Course.objects.all()),
    )
    article.tags.add(tag1)
    article.keywords.add(keyword)
    article.save()

    # 生成 100 篇英文博客文章

    print('create some faked posts published within the past year')
    fake = faker.Faker()  # English
    for _ in range(100):
        m = random.sample('abcdefghijklmnopqrstuvwxyz', 5)
        s = ''.join(m)
        tags = Tag.objects.order_by('?')
        tag1 = tags.first()
        tag2 = tags.last()
        cate = Category.objects.order_by('?').first()
        created_time = fake.date_time_between(start_date='-1y', end_date="now",
                                              tzinfo=timezone.get_current_timezone())
        counter = random.randint(0,100)
        post = Article.objects.create(
            title=fake.sentence().rstrip('.'),
            body='\n\n'.join(fake.paragraphs(10)),
            created_time=created_time,
            category=cate,
            author=user,
            counter=counter,
            slug=s,
            course=random.choice(Course.objects.all()),
        )
        post.tags.add(tag1, tag2)
        post.save()

    # 生成数据，传入了一个语言代码 zh_CN，这将生成中文的虚拟数据，而不是默认的英文。

    fake = faker.Faker('zh_CN')
    for _ in range(100):  # Chinese
        m = random.sample('abcdefghijklmnopqrstuvwxyz', 5)
        s = ''.join(m)
        tags = Tag.objects.order_by('?')
        tag1 = tags.first()
        tag2 = tags.last()
        cate = Category.objects.order_by('?').first()
        created_time = fake.date_time_between(start_date='-1y', end_date="now",
                                              tzinfo=timezone.get_current_timezone())
        counter = random.randint(0, 100)
        post = Article.objects.create(
            title=fake.sentence().rstrip('.'),
            body='\n\n'.join(fake.paragraphs(10)),
            created_time=created_time,
            category=cate,
            author = user,
            counter = counter,
            slug=s,
            course=random.choice(Course.objects.all()),
        )
        post.tags.add(tag1, tag2)
        post.save()


    # 评论
    print('create some comments')
    for post in Article.objects.all()[:20]:
        post_created_time = post.created_time
        delta_in_days = '-' + str((timezone.now() - post_created_time).days) + 'd'
        for _ in range(random.randrange(3, 15)):
            Comment.objects.create(
                author=user,
                belong=post,
                content=fake.paragraph(),
                created_time=fake.date_time_between(
                    start_date=delta_in_days,
                    end_date="now",
                    tzinfo=timezone.get_current_timezone()),
            )

    print('done!')